import { TimeOperations, filterTime } from '@/utils/TimeUtils'
import type { DateItem, TimeItem } from './type'
import {
  GeneratePredetermineDatesAndTimeRangesNeedInfo,
  GeneratedPredetermineDatesAndTimeRangesInfo
} from './utils.type'
// 预定时间选择数据生成器
export class PredetermineDatesAndTimeRangesGenerator {
  // 获取日期的Label
  private static getYmdLabel(index: number, timeOperations: TimeOperations): string {
    const indexAndFirstLabel = ['今天', '明天']
    const dateFormatStr =
      timeOperations.getCoreDate().getFullYear() === new Date().getFullYear() ? 'MM-dd' : 'yyyy-MM-dd'
    return (
      (indexAndFirstLabel[index] ?? timeOperations.formatDate(dateFormatStr)) + `(${timeOperations.getDayOfWeek()})`
    )
  }
  // 过滤空的time头部
  public static filterEmptyHeadDateTime(dateTimes: DateItem[]): DateItem[] {
    if (dateTimes == null || dateTimes.length == 0) return dateTimes
    for (let i = 0; i < dateTimes.length; i++) {
      const tiems = dateTimes[i]
      if (tiems == null || tiems.times == null || tiems.times.length == 0) {
        dateTimes.splice(i, 1)
      } else {
        break
      }
    }
    return dateTimes
  }
  public static gen(
    source: GeneratePredetermineDatesAndTimeRangesNeedInfo,
    deliveryTime?: number
  ): GeneratedPredetermineDatesAndTimeRangesInfo | null {
    let advanceBookingDays = 0
    if (source == null || (advanceBookingDays = source.predetermineDaysValidPeriod.length) === 0) return null
    const content = new GeneratedPredetermineDatesAndTimeRangesInfo()
    // 给容器赋于初始值
    content.datesTimes = []
    const formatTemplate = 'yyyy-MM-dd'
    for (let i = 0; i < advanceBookingDays; i++) {
      const timeOperations = new TimeOperations().addDay(i)
      const lastYmd = timeOperations.formatDate(formatTemplate)
      const daysAndTimesList = source.predetermineDaysValidPeriod
      const collectTimes: TimeItem[] = []
      // daysAndTimesList可能是空的，当是空的，那collectTimes应该没有的
      if (daysAndTimesList[i] != null) {
        // 如果是今天，那需要考虑今天
        if (i === 0) daysAndTimesList[i] = filterTime(daysAndTimesList[i])
        let isExceedingSpecificDay = false
        for (const time of daysAndTimesList[i]) {
          timeOperations.update(undefined, time.startTime)
          // eslint-disable-next-line no-constant-condition
          while (true) {
            timeOperations.addMinutes(source.makeTime)
            if (
              (isExceedingSpecificDay = timeOperations.formatDate(formatTemplate) !== lastYmd) ||
              !timeOperations.hmsLt(time.endTime)
            ) {
              break
            }

            collectTimes.push({
              pmTime: timeOperations.formatDate('HH:mm'),
              time: timeOperations
                .copyInstance()
                .addMinutes(deliveryTime ?? 0)
                .formatDate('HH:mm')
            })
          }
          // 如果超过了i对应的天数，那就下一天
          if (isExceedingSpecificDay) {
            // 将date部分设置回来.因为后面还要用到它的YMD部分
            timeOperations.update(lastYmd)
            // 如果已经超过了i对应的那天，那就跳过i对应的后面time了
            break
          }
        }
      }

      // 将times组装到day
      content.datesTimes[i] = {
        ymdLabel: this.getYmdLabel(i, timeOperations),
        ymdFormat: lastYmd,
        times: collectTimes
      }
    }
    // 过滤掉空头
    this.filterEmptyHeadDateTime(content.datesTimes)
    // 注入“尽快送达” ,即使用immediately代表
    const firstDay = content.datesTimes[0]
    if (firstDay != null && firstDay.times.length > 0) {
      content.immediatePredetermineTime = {
        dateItem: firstDay,
        timeItem: firstDay.times[0]
      }
    }
    console.log('生成结果：', content)
    return content
  }
}
